package com.bitin.adorn.modules.system.service.impl;

import com.bitin.adorn.common.constant.RedisConstants;
import com.bitin.adorn.modules.system.domain.Config;
import com.bitin.adorn.modules.system.repository.ConfigRepository;
import com.bitin.adorn.modules.system.service.ConfigService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置Service接口实现
 *
 * @author Mr.Lu
 * @since 2024/12/30 10:55
 */
@Service
@RequiredArgsConstructor
public class ConfigServiceImpl implements ConfigService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ConfigRepository configRepository;

    /**
     * 刷新系统配置缓存
     *
     * @return 是否刷新成功
     */
    @Override
    public boolean refreshCache() {
        redisTemplate.delete(RedisConstants.SYSTEM_CONFIG_KEY);
        List<Config> list = this.configRepository.findAll();
        if (CollectionUtils.isEmpty(list)) return false;

        Map<String, String> map = list.stream().collect(Collectors.toMap(Config::getConfigKey, Config::getConfigValue));
        redisTemplate.opsForHash().putAll(RedisConstants.SYSTEM_CONFIG_KEY, map);
        return true;
    }

    /**
     * 获取系统配置
     *
     * @param key 配置键
     * @return 配置值
     */
    @Override
    public Object getSystemConfig(String key) {
        if (StringUtils.isBlank(key)) return null;

        return redisTemplate.opsForHash().get(RedisConstants.SYSTEM_CONFIG_KEY, key);
    }

    public List<Config> list(){
        return this.configRepository.findAll();
    }
}
